package com.hack.qiaoqiao.serve;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;

public class FileUpdata extends AsyncTask<Object,Void,Object> {
	private String Url=null;
	private List<File> files = null;
	
	
	public FileUpdata(String url){
		this.Url = url;
		files = new ArrayList<File>();
	}
	
	public void addFile(File file){
		if (file == null || file.exists() || file.canRead()){
			return ;
		}else{
			for (int i = 0 ; i < files.size(); i++){
				if (file.getPath().equalsIgnoreCase(files.get(i).getName())){
					return ;
				}
			}
			files.add(file);
		}
	}


	@Override
	protected Object doInBackground(Object... arg0) {
		// TODO Auto-generated method stub
		for (int i = 0;i< files.size();i++ ){
			HttpClient httpClient = new DefaultHttpClient();
			try{
				FileEntity entity =new FileEntity(files.get(i),"binary/octet-stream");
				StringBuilder curUrl = new StringBuilder(Url);
				curUrl.append("?fileName="+files.get(i).getName());
				HttpPost httppost = new HttpPost(curUrl.toString());
				httppost.setEntity(entity);
				
				HttpResponse response = httpClient.execute(httppost);
				int resultCode = response.getStatusLine().getStatusCode();
				if (resultCode != HttpStatus.SC_OK){
					throw new Exception("updata file"+files.get(i).getPath()+"failed ,wrong code is :" +resultCode+"resean : "+response.getStatusLine().getReasonPhrase());
				}
				
			}catch (Exception e){
				e.printStackTrace();
			}
			finally {
				if (httpClient != null && httpClient.getConnectionManager() != null){
					httpClient.getConnectionManager().shutdown();
				}
			}
		}
		return null;
	}
}
